package org.cyz.tools.common.util;

import javafx.event.EventHandler;
import javafx.scene.control.TextArea;
import javafx.scene.input.KeyEvent;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * @author abccy
 * @title: ConsoleUtil
 * @projectName RedisGUI
 * @description: TODO
 * @date 2020-9-1517:41
 */
public class ConsoleUtil extends CmdUtil {

    private static String jarPath;
    private static String basePath;
    private KeyBoardUtil keyBoardUtil = new KeyBoardUtil();


    /**
     * 填充控制台的头信息
     *
     * @return
     */
    public static String consoleHeader() {
        return  System.getProperty("user.name") + "@" + RedisUtil.connection + ">";
    }

    /**
     * 执行命令
     *
     * @param cmd
     * @return
     */
    public static String inputMsg(String cmd) {
        cmd= cmd.split("\n")[0];
        ArrayList<String> cmds = new ArrayList(Arrays.asList(cmd.split(" ")));
        if (cmds.size() < 2) {
            //redis系统命令
            return executeSignCmd(cmd);
        }
        try {
            String val = cmds.remove(0);
            return execRedisCommand(null, val, cmds.toArray(new String[cmds.size()])).toString();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 初始化控制台
     * @param inputConsole
     * @param showConsole
     */
    public void initConsole(TextArea inputConsole,TextArea showConsole) {
        inputConsole.setWrapText(true);
        inputConsole.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent keyEvent) {
                keyBoardUtil.inputEvent(keyEvent, inputConsole);
            }
        });
        inputConsole.setOnKeyPressed(new EventHandler<KeyEvent>() {
            @Override
            public void handle(KeyEvent keyEvent) {
                keyBoardUtil.inputContent(keyEvent, inputConsole, showConsole);
            }
        });
    }
}
